<template>
  <view class="scan size">
    <view class="sectionview">
      <view id="qr-reader" style="width:100%;height:100%;"></view>
    </view>
  </view>
</template>
<script>
import { Html5Qrcode } from "html5-qrcode";
export default {
  data() {
    return {
      cameraId: '',
    };
  },
  mounted() {
    this.init();
  },
  beforeDestroy() {
    this.stop();
  },
  methods: {
    //返回结果
    getCode(id) {
      if (!id) return;
      this.$emit('GetCode', id);
    },
    init() {
      //需要加载时间建议延时一点再获取设备列表
     this.$nextTick(() => {
       setTimeout(() => {
         this.getCameras();
       }, 200);
      });
    },
    stop() {
      this.html5QrCode
          .stop()
          .then(ignore => {
            // QR Code scanning is stopped.
            console.log('QR Code scanning stopped.');
          })
          .catch(err => {
            // Stop failed, handle it.
            console.log('Unable to stop scanning.');
          });
    },
    start() {
      this.html5QrCode = new Html5Qrcode('qr-reader');
      this.html5QrCode
          .start(
              this.cameraId,//500毫秒扫描一次
              {
                fps: 2, // sets the framerate to 10 frame per second
                qrbox: { width: 250, height: 250 }, // sets only 250 X 250 region of viewfinder to
              },
              qrCodeMessage => {
                // do something when code is read. For example:
                if (qrCodeMessage) {
                  uni.showToast({
                    title: '扫描成功',
                    icon: 'success',
                    //显示持续时间为 2秒
                    duration: 2000
                  })
                  console.log(`QR Code detected: ${qrCodeMessage}`)
                  this.getCode(qrCodeMessage);
                  // this.stop();
                }
              },
              errorMessage => {
                // parse error, ideally ignore it. For example:
                // console.log(`QR Code no longer in front of camera.`);
              }
          )
          .catch(err => {
            // Start failed, handle it. For example,
            console.log(`Unable to start scanning, error: ${err}`);
            uni.showToast({
              title: '启动摄像头失败',
              icon: 'error',
              //显示持续时间为 2秒
              duration: 1200
            })
          });
    },
    getCameras() {
      Html5Qrcode.getCameras()
          .then(devices => {
            /**
             * devices would be an array of objects of type:
             * { id: "id", label: "label" }
             */
            if (devices && devices.length) {
              if (devices.length > 1) {
                this.cameraId = devices[1].id;
              } else {
                this.cameraId = devices[0].id;
              }
              console.log(this.cameraId, 'cameraId');
              uni.showToast({
                title: '获取摄像头成功',
                icon: 'success',
                //显示持续时间为 2秒
                duration: 1200
              })
              this.start();
            }
          })
          .catch(err => {
            uni.showToast({
              title: '获取摄像头失败',
              icon: 'error',
              //显示持续时间为 2秒
              duration: 1200
            })
          });
    },
  }
};
</script>
<style lang="less">
.scan {
  width: 100%;
  height: calc(100vh - 60px);
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  background-color: #000;

  .sectionview {
    width: 100%;
    position: relative;
    overflow: hidden;
  }
}
</style>
